package com.motu.monstercity.server.game.base;

import com.motu.monstercity.server.game.commondata.build.BuildConstant;
import com.motu.monstercity.server.game.commondata.partner.PartnerConstant;
import com.motu.monstercity.server.game.commondata.partner.PartnerMain;
import com.motu.monstercity.server.game.logic.PartnerManager;
import com.motu.monstercity.server.game.logic.RewardItem;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.SensitivewordEngine;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

//  通用的工具类
public class CommonUtils {
    private static Logger logger = LoggerFactory.getLogger(CommonUtils.class);

    // itemId;itemNum;itemId;itemNum;itemId;itemNum; 格式的字符串转成
    public static List<RewardItem> takeReawrdItemFromStr(String string) {
        List<RewardItem> result = new ArrayList<>();
        try {
            String[] strArray = string.replace(" ", "").split(";");// 去除空格 按;划分
            for (int i = 0; i < strArray.length; i++) {
                if (i%2 == 0) {
                    int itemId = Integer.parseInt(strArray[i]);
                    long itemNum = Long.parseLong(strArray[i+1]);
                    RewardItem rewardItem = new RewardItem(itemId, itemNum);
                    result.add(rewardItem);
                }
            }
        } catch (Exception e) {}
        return result;
    }

    public static List<RewardItem> takeReawrdItemFromStr(int itemId, long itemNum) {
        List<RewardItem> result = new ArrayList<>();
        RewardItem rewardItem = new RewardItem(itemId, itemNum);
        result.add(rewardItem);
        return result;
    }

    /**
     *  修改rewardItemList 的道具数量，增加百分比或是减少百分比
     * @param rewardItemList
     * @param per -2000 表示数量减少20%，如原来是200个，则扣完只需160个
     */
    public static void modifyRewardItem(List<RewardItem> rewardItemList, int per) {
        for (RewardItem rewardItem : rewardItemList) {
            long newNum = CommonUtils.countPerValue(rewardItem.getItemNum(), per);
            rewardItem.setItemNum(newNum);
        }
    }

    // 获取百分比计算后的值
    public static long countPerValue(long value, int per) {
        double restul = value;
        return countPerValue(restul, per);
    }

    public static long countPerValue(int value, int per) {
        double restul = value;
        return countPerValue(restul, per);
    }

    // 获取百分比计算后的值
    public static long countPerValue(double value, int per) {
        value = value + value * per / 10000;
        long aa = (long)Math.floor(value);
        if (aa < 0) {
            return 0;
        } else {
            return aa;
        }
    }

    //  判断rewardItemList 是否包含有某个itemid
    public static boolean checkContainsItemId(List<RewardItem> rewardItemList, int itemId) {
        for (RewardItem rewardItem : rewardItemList) {
            if (rewardItem.getItemId() == itemId)  {
                return true;
            }
        }
        return false;
    }

    // 合并相同itemid的数量
    public static List<RewardItem> mergeItemList(List<RewardItem> list) {
        List<RewardItem> result = new ArrayList<>();
        for (RewardItem rewardItem : list) {
            addRewardItem(result, rewardItem.getItemId(), rewardItem.getItemNum());
        }
        return result;
    }

    //数量 x N倍
    public static void multipleItemList(List<RewardItem> list, int mul) {
        for (RewardItem rewardItem : list) {
            long itemNum = rewardItem.getItemNum();
            rewardItem.setItemNum(itemNum * mul);
        }
    }

    // 把itemid,itemnum 添加到List<RewardItem>, 相同itemid的数量叠加
    public static void addRewardItem(List<RewardItem> list, int itemId, long itemNum) {
        boolean isAdd = false;
        for (RewardItem rewardItem : list) {
            if (rewardItem.getItemId() == itemId) {
                long newNum = rewardItem.getItemNum() + itemNum;
                rewardItem.setItemNum(newNum);
                isAdd = true;// 已经添加过了
            }
        }
        if (!isAdd) {
            RewardItem rewardItem = new RewardItem(itemId, itemNum);
            list.add(rewardItem);
        }
    }

    // 两个List<RewardItem>，合并成一个，相关Itemid数量相加
    public static void mergeItemList(List<RewardItem> list, List<RewardItem> list2) {
        for (RewardItem rewardItem : list2) {
            addRewardItem(list, rewardItem.getItemId(), rewardItem.getItemNum());
        }
    }

    // aa;bb;cc;dd  转成jsonarray
    public static JsonArray strToJsonArray(String str) {
        JsonArray jsonArray = new JsonArray();
        if (Tool.isEmpty(str)) {
            return jsonArray;
        }

        String[] strArray = str.replace(" ", "").split(";");// 去除空格
        try {
            for (int i = 0; i < strArray.length; i++) {
                jsonArray.add(Integer.parseInt(strArray[i]));
            }
        } catch (Exception e) {}

        return jsonArray;
    }

    // 0;10;20;30  转成整数数组
    public static int[] strToIntArray(String str) {
        return Tool.strToIntArray(str, ";");
    }

    // 打印物品列表,调试用
    public static void printRewwardItemList(List<RewardItem> rewardItems) {
        for (RewardItem rewardItem : rewardItems) {
            logger.info("itemid:" + rewardItem.getItemId() + " num:" + rewardItem.getItemNum());
        }
    }

    /**
     * 数字转成字符串,不足前面补0, 入n=1,len=4 返回0001 字符串
     * @param n 数值
     * @param len 长度
     * @return
     */
    public static String numberToString(long n, int len) {
        String nn = String.valueOf(n);
        int ll = nn.length();
        String pre = "";
        for (int i=ll; i<len; i++) {
            pre += "0";
        }
        return pre + nn;
    }

    /**
     * 验证玩家输入的字符串是否正确
     * @param string
     * @param lengthMin 最小长度
     * @param lengthMax 最大长度
     * @param enterAble 支持回车符号
     * @return
     */
    public static ErrorWord checkString(String string, int lengthMin, int lengthMax, boolean enterAble){
        string = Tool.dropFourByte(string);//将字符串中的苹果表情符过滤掉
        if (Tool.isEmpty(string)) {
            return ErrorWord.NOT_DATA;//
        }
        if (Tool.getStrByteLen(string.replace(" ","")) == 0) {// 不能是一串空格
            return ErrorWord.WORD_LENGTH_WRONG;//长度不符合规范
        }

        int len = Tool.getStrByteLen(string);
        if(len < lengthMin || len > lengthMax){
            return ErrorWord.WORD_LENGTH_WRONG;//长度不符合规范
        }
        if(!Tool.checkFourByte(string)){
            return ErrorWord.CHAR_NOT_ALLOW;
        }
        char enter = 13;//回车字符
        char tt = 39;//单引号
        char tab = 9;//tab键
        if (string.indexOf('#') != -1 || string.indexOf('$') != -1 || string.indexOf(tt) != -1 || string.indexOf(tab) != -1) {
            return ErrorWord.CHAR_NOT_ALLOW;
        }

        if (!enterAble && (string.indexOf('\n') != -1|| string.indexOf(enter) != -1)) {
            return ErrorWord.CHAR_NOT_ALLOW;// 过滤回车符号
        }

        // null在敏感词库中过滤不掉，需要特殊处理
        if (string.equalsIgnoreCase("null")){
            return ErrorWord.BAD_WORD;
        }
        //先检查是否有敏感词
        if (SensitivewordEngine.isContaintSensitiveWord(string, SensitivewordEngine.MinMatchType)){
            return ErrorWord.BAD_WORD;
        }
        return ErrorWord.SUCCESS;
    }

    // 是否在同个小时内
    public static boolean isSameHour(long time1, long time2) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time1 * 1000);
        int hour1 = cal.get(Calendar.HOUR_OF_DAY);//当前是第几点

        cal.setTimeInMillis(time2 * 1000);
        int hour2 = cal.get(Calendar.HOUR_OF_DAY);//当前是第几点

        return hour1 == hour2;
    }

    /**
     * @param c 拼接字符
     */
    public static String strArrayToString(String[] array, String c) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < array.length; i++) {
            if (i != 0) {
                sb.append(c);
            }
            sb.append(array[i]);
        }
        return sb.toString();
    }

    /**
     * 拼接两个数组，生成新数组
     * <p>比如消耗日志参数要追加参数
     *
     * @param sourceArray 排在前面的
     * @param appendArray 后面加入的数据
     */
    public static <T> T[] appendArrays(T[] sourceArray, T[] appendArray) {
        T[] newLogParams = Arrays.copyOf(sourceArray, sourceArray.length + appendArray.length);
        System.arraycopy(appendArray, 0, newLogParams, sourceArray.length, appendArray.length);
        return newLogParams;
    }

    public static String[] strToArray(String value, String c) {
        String[] strArray = value.replace(" ", "").split(c);// 去除空格
        return strArray;
    }

    /**
     * 数值转字符串
     * @param intArray
     * @param c 拼接字符
     * @return
     */
    public static String intArrayToString(int[] intArray, String c) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < intArray.length; i++) {
            if (i != 0) {
                sb.append(c);
            }
            sb.append(intArray[i]);
        }
        return sb.toString();
    }

    // 获取当前时间的整分钟的时间戳。若2025-04-07 17:24:59 时间戳，则返回2025-04-07 17:24:00的时间戳
    public static long getMinuteTime(long time) {
        String tt = TimeUtils.getTimeStr(time);
        return TimeUtils.getTimeStrIntValue(tt + ":00");
    }

    /**
     * 根据权重数值，返回随机结果 如策划配置0;10000;15000;18000 这样的权重数组，随机到15000，则返回结果是3
     * @param rates 0;10000;15000;18000
     * @return
     */
    public static int getRandom(int[] rates) {
        int random = Tool.getWeightIndex(rates);
        return random + 1;
    }


    // id;weight;id;weight;id;weight; 格式的字符串转成
    public static int takeParamByWeightParamStr(String string) {
        try {
            String[] strArray = string.strip().split(";");// 去除空格 按;划分
            int[] ids = new int[strArray.length/2];
            int[] rates = new int[strArray.length/2];
            for (int i = 0; i < strArray.length; i++) {
                if (i%2 == 0) {
                    ids[i/2] = Integer.parseInt(strArray[i]);
                    rates[i/2] = Integer.parseInt(strArray[i+1]);
                }
            }
            int random = Tool.getWeightIndex(rates);
            return ids[random];

        } catch (Exception e) {}

        return 0;
    }

    // 转成itemid;num;itemid;num 格式的字符串
    public static String getRewardString(List<RewardItem> rewardItems) {
        String str = "";
        int max = rewardItems.size();
        for (int i=0; i<max; i++) {
            RewardItem rewardItem = rewardItems.get(i);
            str += rewardItem.getItemId() + ";" + rewardItem.getItemNum();
            if (i < max - 1) {
                str += ";";
            }
        }
        return str;
    }

    // rewarditem 转成itemid;num 格式的字符串
    public static String getRewardString(RewardItem rewardItem) {
        return rewardItem.getItemId() + ";" + rewardItem.getItemNum();
    }

    // 转成itemid;num 格式的字符串
    public static String getRewardString(int itemId, long itemNum) {
        return itemId + ";" + itemNum;
    }
}
